package org.footballmanager.pandafootball.system.controller.hy;

import org.footballmanager.pandafootball.common.constants.Constants;
import org.footballmanager.pandafootball.common.util.StringUtil;
import org.footballmanager.pandafootball.system.controller.BaseController;
import org.footballmanager.pandafootball.system.domain.*;
import org.footballmanager.pandafootball.system.domain.enums.JNFL;
import org.footballmanager.pandafootball.system.form.impl.FootGpSearchForm;
import org.footballmanager.pandafootball.system.service.*;
import org.footballmanager.pandafootball.system.service.impl.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.support.SessionStatus;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.text.DecimalFormat;
import java.util.Date;

@Controller
@SessionAttributes("footGpSearchForm")
@RequestMapping("/hy/footGp")
public class HyGpController extends BaseController {
    /* 实体名称 */
    private static final String ENTITYNAME = "footGp";
    private static final String ADDPAGE = String.format(Constants.ADDPAGE, Constants.HY, ENTITYNAME);
    private static final String LISTPAGE = String.format(Constants.LISTPAGE, Constants.HY, ENTITYNAME);
    private static final String REDIRECT = String.format(Constants.REDIRECT, Constants.HY, ENTITYNAME);

    @Autowired
    private FootGpService footGpService;
    @Autowired
    private FootPersonService footPersonService;
    @Autowired
    private FootUserPersonService footUserPersonService;
    @Autowired
    private FootTeamService footTeamService;
    @Autowired
    private FootZnxService footZnxService;
    @Autowired
    private FootZjService footZjService;
    @Autowired
    private FootTaxService footTaxService;
    @Autowired
    private FootTableTitleService footTableTitleService;
    @Autowired
    private RedisService redisService;

    /**
     * 初始化
     *
     * @param map              参数
     * @param footGpSearchForm 条件参数
     */
    @ModelAttribute
    public void init(Model map, HttpServletRequest request, @ModelAttribute FootGpSearchForm footGpSearchForm) {
        map.addAttribute("head", footTableTitleService.findByTableName(Constants.PERSONTABLE));
        map.addAttribute("djList", redisService.get("listdj"));
        footGpService.clear(request);
        FootUser user = (FootUser) request.getSession().getAttribute(Constants.USER);
        map.addAttribute("qyList", footUserPersonService.findCanGpPerson(user.getId()));
        FootGpSearchForm newFootGpSearchForm = new FootGpSearchForm();
        if (footGpSearchForm != null) {
            newFootGpSearchForm = footGpSearchForm;
        }
        map.addAttribute(String.format(Constants.FORMNAME, ENTITYNAME), newFootGpSearchForm);
    }

    //挂牌中心
    @RequestMapping(value = "/search")
    public String search(Model map, @ModelAttribute FootGpSearchForm footGpSearchForm) {
        footGpSearchForm.setCj(false);
        footGpService.search(ENTITYNAME, map, footGpSearchForm);
        return LISTPAGE;
    }

    //我的挂牌球员
    @RequestMapping(value = "/mySearch", method = RequestMethod.GET)
    public String mySearch(Model map, HttpServletRequest request, @ModelAttribute FootGpSearchForm footGpSearchForm) {
        FootUser user = (FootUser) request.getSession().getAttribute(Constants.USER);
        footGpSearchForm.setCj(false);
        footGpSearchForm.setSellUserId(user.getId());
        footGpService.search(ENTITYNAME, map, footGpSearchForm);
        return "hy/footGp/MyList";
    }

    @RequestMapping(value = "/delete", method = RequestMethod.GET)
    public String delete(@RequestParam Long id, HttpServletRequest request) {
        footGpService.delete(id, request);
        return "redirect:/hy/footGp/mySearch";
    }

    @RequestMapping(value = "/deleteall", method = RequestMethod.POST)
    public String deleteall(HttpServletRequest request, @ModelAttribute FootGpSearchForm footGpSearchForm) {
        footGpService.deleteAll(footGpSearchForm, request);
        return "redirect:/hy/footGp/mySearch";
    }

    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public String openAddPage(Model map, HttpServletRequest request) {
        Long userId = (Long) request.getSession().getAttribute(Constants.USERID);
        map.addAttribute("footPersonList", footUserPersonService.findFootPersonByUserId(userId, request));
        FootGp gp = new FootGp();
        gp.setSellUserId(userId);
        gp.setGpsj(new Date());
        map.addAttribute(ENTITYNAME, gp);
        return ADDPAGE;
    }

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public String save(@Valid @ModelAttribute FootGp footGp, BindingResult bindingResult,
                       HttpServletRequest request, SessionStatus s, Model map) {
        Long userId = (Long) request.getSession().getAttribute(Constants.USERID);
        if (!bindingResult.hasErrors()) {
            FootUserPerson fup = footUserPersonService.get(footGp.getFupId());
            fup.setGpzt(1);
            footUserPersonService.updateNotNull(fup, request);
            footGp.setQyId(fup.getQyId());
            FootPerson fp = footPersonService.get(fup.getQyId());
            if (footGp.getYkj() < Double.valueOf(fp.getQysj()) * 0.8 || footGp.getYkj() > Double.valueOf(fp.getQysj()) * 2) {
                bindingResult.rejectValue("ykj", Constants.MISFORMAT, "一口价不能小于球员身价的80%且不能大于球员身价的200%");
                map.addAttribute("footPersonList", footUserPersonService.findFootPersonByUserId(userId, request));
                return ADDPAGE;
            }
            footGp.setCj(false);
            footGp.setQyName(fp.getName());
            footGp.setYw(fp.getYw());
            footGp.setGpsj(new Date());
            footGpService.save(footGp, request);
            s.setComplete();
            return REDIRECT;
        } else
            map.addAttribute("footPersonList", footUserPersonService.findFootPersonByUserId(userId, request));
        return ADDPAGE;
    }

    @RequestMapping(value = "/isMyGp", method = RequestMethod.POST)
    @ResponseBody
    public JsonReturn isMyGp(HttpServletRequest request, @RequestParam Long id) {
        FootUser user = (FootUser) request.getSession().getAttribute(Constants.USER);
        FootTeam ft = footTeamService.getTeamByUserid(user.getId());
        FootGp fg = footGpService.get(id);
        return processMyGp(user, ft, fg);
    }

    private JsonReturn processMyGp(FootUser user, FootTeam ft, FootGp fg) {
        if (!user.getJoins() || null == ft.getQdId()) {
            return new JsonReturn("对不起，系统没有找到您的球队！");
        }
        if (fg == null) {
            return new JsonReturn("对不起，没有找到数据！");
        }
        if (fg.getSellUserId().equals(user.getId())) {
            return new JsonReturn("对不起，此球员是您挂牌出售的，请更换！");
        }
        //如果买不起即 一口价大于你的总资金
        if ((fg.getYkj() * (1d + footTaxService.getDealTax())) > ft.getQdZzj()) {
            return new JsonReturn("对不起，您的球队资金不够购买该球员！");
        }
        return new JsonReturn(Constants.OK);
    }

    @RequestMapping(value = "/buy", method = RequestMethod.GET)
    public String buy(HttpServletRequest request, @RequestParam Long id) {
        FootUser user = (FootUser) request.getSession().getAttribute(Constants.USER);
        FootTeam ft = footTeamService.getTeamByUserid(user.getId());
        FootGp fg = footGpService.get(id);
        if (fg != null) {
            fg.setCj(true);
            fg.setBuyUserId(user.getId());
            footGpService.updateNotNull(fg, request);
            if (fg.getFupId() != null) {
                footUserPersonService.delete(fg.getFupId(), request);
            }
            FootPerson fp = footPersonService.get(fg.getQyId());

            footUserPersonService.saveUserPerson(user.getId(), fp, request);
            double result = fg.getYkj() * footTaxService.getDealTax();
            ft.setQdZzj(ft.getQdZzj() - fg.getYkj());
            footTeamService.updateAll(ft, request);
            FootTeam ft2 = footTeamService.getTeamByUserid(fg.getSellUserId());
            ft2.setQdZzj(ft2.getQdZzj() + result);
            footTeamService.updateAll(ft2, request);
            footZnxService.sendZnx(user.getId(), fg.getSellUserId(), user.getNike() + "已经成功从挂牌中心抢走了玩家" +
                            fg.getSellUserName() + "的球员" + StringUtil.getFullNameFromPerson(fp),
                            footTeamService.getLogoByUserid(user.getId()), null, request);
            footZjService.sendZj(user.getId(), fg.getYkj(), false,
                    "因购买玩家" + fg.getSellUserName() + "的球员" + StringUtil.getFullNameFromPerson(fp) +
                            "，花费:" + new DecimalFormat(",###").format(fg.getYkj()) + "PB(含税),当前球队的总资金为:" +
                            new DecimalFormat(",###").format(ft.getQdZzj()) + "PB", request);
            footZjService.sendZj(fg.getSellUserId(), result, true,
                    "因球员您的球员" + StringUtil.getFullNameFromPerson(fp) + "被抢购,获得:" +
                            new DecimalFormat(",###").format(result) + "PB,当前球队的总资金为:" +
                            new DecimalFormat(",###").format(ft2.getQdZzj()) + "PB", request);
        }
        return REDIRECT;
    }

    @RequestMapping(value = "/view", method = RequestMethod.GET)
    public String openViewPage(Model map, @RequestParam Long id,
                               @ModelAttribute FootGpSearchForm footGpSearchForm) {
        FootGp gp = footGpService.get(id);
        map.addAttribute(ENTITYNAME, gp);
        map.addAttribute("footPerson", footPersonService.get(gp.getQyId()));
        map.addAttribute("basicSkills", footTableTitleService.findByTableNameAndJnfl(Constants.PERSONTABLE, JNFL.BASIC));
        map.addAttribute("linkageSkills", footTableTitleService.findByTableNameAndJnfl(Constants.PERSONTABLE, JNFL.LINKAGE));
        return "hy/footGp/QyView";
    }
}
